//
//  AppDelegate.m
//  GainInvest
//
//  Created by 王玉龙 on 17/2/7.
//  Copyright © 2017年 longlong. All rights reserved.
//


#define WeChatAppId @"wxab7216f0d45a0485"
#define WeChatAppSecret @"81adf968f08fc8c7d416ec300ddd264f"

#import "AppDelegate.h"
#import "MainTabBarController.h"
#import "IntroPageViewController.h"


#import <UMSocialCore/UMSocialCore.h>
#import "SPayClient.h"

#import "AppDelegate+UMPush.h"
#import "AppDelegate+IM.h"
#import "AppDelegate+LaunchImage.h"

#import "MessageTableDAO.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    
    
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackTranslucent];
    [[UINavigationBar appearance] setBackgroundImage:[MainTabBarController loadTabBarAndNavBarBackgroundImage] forBarMetrics:UIBarMetricsDefault];


    
    if ([IntroPageViewController isFirstLaunch] )
    {
        IntroPageViewController *introPage = [[IntroPageViewController alloc]init];
        self.window.rootViewController = introPage;
    }
    else
    {
        MainTabBarController *mainController = [MainTabBarController shareMainController];
        
        self.window.rootViewController = mainController;
    }
    
    //配置启动页
    [self launchApplication:application didFinishLaunchingWithOptions:launchOptions];
    //友盟推送
    [self umPushApplication:application didFinishLaunchingWithOptions:launchOptions];
    //容联云通讯
    [self imPushApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    //支付信息配置
    {
        [WXApi registerApp:WeChatAppId];

        SPayClientWechatConfigModel *wechatConfigModel = [[SPayClientWechatConfigModel alloc] init];
        wechatConfigModel.appScheme = WeChatAppId;
        wechatConfigModel.wechatAppid = WeChatAppId;
        wechatConfigModel.wapAppScheme = WeChatAppId;
        wechatConfigModel.isEnableMTA =YES;
        
        
        //配置微信APP支付
        [[SPayClient sharedInstance] wechatpPayConfig:wechatConfigModel];
        [[SPayClient sharedInstance] application:application
                   didFinishLaunchingWithOptions:launchOptions];
    }
    
    
    
    
    return YES;
}



- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    [MessageTableDAO getUnReadMessageCountCompletionBlock:^(NSUInteger count) {}];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [[SPayClient sharedInstance] applicationWillEnterForeground:application];
    
}


- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark -

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    NSLog(@"application ===== %@",url.absoluteString);
    
    if ([url.absoluteString containsString:WeChatAppId])
    {
        if ([url.absoluteString containsString:@"pay"])//微信支付
        {
            NSString *resultString = [url.absoluteString componentsSeparatedByString:@"&ret="].lastObject;
            if ([resultString isEqualToString:@"0"])
            {
                NSLog(@"支付成功");
            }
            else
            {
                NSLog(@"支付失败");
            }
            return  [[SPayClient sharedInstance] application:application handleOpenURL:url];
        }
        else if ([url.absoluteString containsString:@"oauth?code="])//微信登录
        {
            //微信登录使用的是友盟
            return [[UMSocialManager defaultManager] handleOpenURL:url];
        }
        else//微信分享
        {
            return  [WXApi handleOpenURL:url delegate:self];
        }
    }
    else
    {
        //QQ登录
        return [[UMSocialManager defaultManager] handleOpenURL:url];
    }

    
    return YES;
    
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    
    NSLog(@"openURL ===== %@",url);
    NSLog(@"sourceApplication ===== %@",sourceApplication);

    if ([sourceApplication containsString:@"com.tencent.xin"])
    {
        if ([url.absoluteString containsString:@"pay"])//微信支付
        {
            NSString *resultString = [url.absoluteString componentsSeparatedByString:@"&ret="].lastObject;
            if ([resultString isEqualToString:@"0"])
            {
                NSLog(@"支付成功");
            }
            else
            {
                NSLog(@"支付失败");
            }
            [[SPayClient sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
            return YES;
        }
        else if ([url.absoluteString containsString:@"oauth?code="])//微信登录
        {
            //微信登录使用的是友盟
            return [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
        }
        else
        {
            //微信分享
            BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
            NSLog(@"url %@ isSuc %d",url,isSuc == YES ? 1 : 0);
            return  isSuc;
        }
    }
    else if ([sourceApplication containsString:@"com.tencent.mqq"])
    {
        //QQ登录
        return [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    }

    
    
    return YES;
}


- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *,id> *)options
{
    
    
    NSLog(@"url ===== %@",url);
    NSLog(@"options ===== %@",options);

    if ([options[@"UIApplicationOpenURLOptionsSourceApplicationKey"] isEqualToString:@"com.tencent.xin"])
    {
        if ([url.absoluteString containsString:@"pay"])//微信支付
        {
            NSString *resultString = [url.absoluteString componentsSeparatedByString:@"&ret="].lastObject;
            if ([resultString isEqualToString:@"0"])
            {
                NSLog(@"支付成功");
            }
            else
            {
                NSLog(@"支付失败");
            }
            [[SPayClient sharedInstance] application:app openURL:url options:options];
            return YES;
        }
        else if ([url.absoluteString containsString:@"oauth?code="])//微信登录
        {
            //微信登录使用的是友盟
            return [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
        }
        else
        {
            //微信分享
            BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
            NSLog(@"url %@ isSuc %d",url,isSuc == YES ? 1 : 0);
            return  isSuc;
        }
    }
    else if ([options[@"UIApplicationOpenURLOptionsSourceApplicationKey"] isEqualToString:@"com.tencent.mqq"])
    {
        //QQ登录
        return [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    }

    
    
    
    return YES;
};

#pragma mark - WeChat Click

/*
 onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面。
 */
-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App提供内容"];
        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        alert.tag = 1000;
        [alert show];
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        WXMediaMessage *msg = temp.message;
        
        //显示微信传过来的内容
        WXAppExtendObject *obj = msg.mediaObject;
        
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App显示内容"];
        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n缩略图:%u bytes\n\n", msg.title, msg.description, obj.extInfo, msg.thumbData.length];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]])
    {
        //从微信启动App
        NSString *strTitle = [NSString stringWithFormat:@"从微信启动"];
        NSString *strMsg = @"这是从微信启动的消息";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}

/*
 如果第三方程序向微信发送了sendReq的请求，那么onResp会被回调。sendReq请求调用后，会切到微信终端程序界面。
 */
-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        NSString *domin = @"";
        if (resp.errStr)
        {
            domin =  resp.errStr;
        }
        
        NSError *error = [NSError errorWithDomain:domin code:resp.errCode userInfo:nil];
        self.libWeChatShareResult(error);
    }
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"GainInvest"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
